<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="4">
              <a-form-item label="部门" prop="type">
                <a-tree-select
                  v-model="queryParam.deptId"
                  style="width: 100%"
                  :dropdown-style="{
                    maxHeight: '400px',
                    overflow: 'auto',
                  }"
                  :tree-data="deptOptions"
                  placeholder="请选择"
                  :replaceFields="{
                    children: 'children',
                    title: 'menuName',
                    key: 'id',
                    value: 'id',
                  }"
                  @change="onMenuTreeChange"
                  allow-clear
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="客户经理">
                <a-select
                  placeholder="请选择客户经理"
                  v-model="queryParam.userId"
                  :getPopupContainer="
                    (triggerNode) => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="d in userNamesList"
                    :key="d.name"
                    :value="d.id"
                    >{{ d.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="线索类型" prop="laiyuanType">
                <a-select
                  placeholder="线索类型"
                  v-model="queryParam.laiyuanType"
                  style="width: 100%"
                  allow-clear
                  @change="onLaiyuanChange"
                  :disabled="disabledLaiyuanType"
                >
                  <a-select-option
                    v-for="(d, index) in [
                      { dictValue: '1', dictLabel: '广告' },
                      { dictValue: '2', dictLabel: '自建' },
                    ]"
                    :key="index"
                    :value="d.dictValue"
                    >{{ d.dictLabel }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="线索来源" prop="type">
                <a-select
                  placeholder="选择线索来源"
                  v-model="queryParam.laiyuan"
                  style="width: 100%"
                  allow-clear
                >
                  <a-select-option
                    v-for="(d, index) in laiyuanOptions"
                    :key="index"
                    :value="d.dictValue"
                    >{{ d.dictLabel }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="4">
              <a-form-item label="城市区域" prop="type">
                <a-select
                  placeholder="所在城市"
                  v-model="queryParam.cityNames"
                  style="width: 100%"
                  mode="multiple"
                  allow-clear
                >
                  <a-select-option
                    v-for="(d, index) in cityOptions"
                    :key="index"
                    :value="d.name.replace('市', '')"
                    >{{ d.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="4" v-if="advanced">
              <a-form-item label="进线时间">
                <a-range-picker
                  v-model="dateRange"
                  valueFormat="YYYY-MM-DD"
                  :show-today="true"
                />
              </a-form-item>
            </a-col>

            <a-col>
              <span
                class="table-page-search-submitButtons"
                style="float: right"
              >
                <a-button type="primary" @click="handleQuery"
                  ><a-icon type="search" />查询</a-button
                >
                <a-button style="margin-left: 8px" @click="resetQuery"
                  ><a-icon type="redo" />重置</a-button
                >
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? "收起" : "展开" }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <a-tabs :activeKey="tabKey" @change="callback">
        <a-tab-pane key="0" tab="全部成本"> </a-tab-pane>
        <a-tab-pane key="1" tab="广告成本"> </a-tab-pane>
        <a-tab-pane key="2" tab="自建成本"> </a-tab-pane>
      </a-tabs>

      <a-table
        :columns="hejicolumns"
        :data-source="hejidata"
        size="middle"
        bordered
        :pagination="false"
        ><span slot="amount" slot-scope="text">
          ¥ {{ formatNumber(text) }}
        </span>
        <span slot="customers" slot-scope="record">
          {{ parseInt(record.customers || 0) }}
        </span>
        <span slot="newCustomers" slot-scope="record">
          {{
            parseInt(record.customers || 0) - parseInt(record.repCustomers || 0)
          }}
        </span>

        <span slot="chengjiaolv" slot-scope="record">
          <span v-if="record.customers !== '0'">
            {{
              parseFloat((record.cjCustomers / record.customers) * 100).toFixed(
                2
              )
            }}
            %
          </span>
          <span v-else> -- </span>
        </span>
        <span slot="hejiroi" slot-scope="record">
          <span v-if="record.zongchengben !== '0.00'">
            {{
              parseFloat(
                (record.huikuanAmount / record.zongchengben) * 100
              ).toFixed(2)
            }}
            %
          </span>

          <span v-else> -- </span>
        </span>
      </a-table>
      <a-card :bordered="false" style="overflow-y: auto; padding-top: 15px">
        <advance-table
          title="资方结算"
          :pagination="{
            current: queryParam.pageNum,
            pageSize: queryParam.pageSize,
            total: total,
            showSizeChanger: true,
            showLessItems: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
            onChange: changeSize,
            onShowSizeChange: onShowSizeChange,
          }"
          tableKey="base-statistics-guanggaochengben-table"
          rowKey="id"
          size="middle"
          @refresh="getList"
          :columns="dynamicColumns"
          :data-source="bizCapBillList"
          :loading="loading"
          :format-conditions="true"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          :scroll="{ x: '100%' }"
        >
          <div class="table-operations" slot="button">
            <a-button
              type=""
              @click="handleExport"
              v-hasPermi="['biz:bizCapBill:export']"
            >
              <a-icon type="download" />导出
            </a-button>
          </div>
          <span slot="type" slot-scope="{ record }">
            {{ typeFormat(record) }}
          </span>

          <!-- <span slot="status" slot-scope="{ record }">
          {{ statusFormat(record) }}
        </span> -->
          <span slot="orgType" slot-scope="{ record }">
            {{ orgTypeFormat(record) }}
          </span>

          <span slot="status" slot-scope="{ record }">
            <a-tag color="orange" v-if="record.status == 0">
              {{ statusFormat(record) }}
            </a-tag>
            <a-tag color="green" v-if="record.status == 1">
              {{ statusFormat(record) }}
            </a-tag>
          </span>
          <span slot="numStr" slot-scope="{ text }">
            ¥ {{ formatNumber(text) }}
          </span>
          <span slot="amount" slot-scope="{ text }">
            ¥ {{ formatNumber(text) }}
            <!-- <span v-if="record.type"> / {{ typeFormat(record) }}</span> -->
          </span>
          <span slot="operation" slot-scope="{ text, record }">
            <a-button
              type="link"
              icon="transaction"
              @click="handleAdd(record)"
              v-if="record.status == 0"
              >结算</a-button
            >
          </span>
          <span slot="rowindex" slot-scope="{ index }">
            {{ index + 1 }}
          </span>
          <span slot="jinjianId" slot-scope="{ text }">
            <a>{{ text }}</a>
          </span>
          <span slot="shangmenCountslv" slot-scope="{ text, record }">
            {{
              parseFloat(
                (record.shangmenCounts / record.yaoyueCounts || 0) * 100
              ).toFixed(2)
            }}%
          </span>
          <span slot="chengjiaoCountslv" slot-scope="{ text, record }">
            {{
              parseFloat(
                (record.chengjiaoCounts / record.jinxianCounts || 0) * 100
              ).toFixed(2)
            }}%
          </span>
          <span slot="youzhiCountslv" slot-scope="{ text, record }">
            {{
              parseFloat(
                (record.youzhiCounts / record.jinxianCounts || 0) * 100
              ).toFixed(2)
            }}%
          </span>
          <span slot="counts" slot-scope="{ text }">
            {{ text || 0 }}
          </span>
          <span slot="cjlv" slot-scope="{ text, record }">
            <span v-if="record.jinxianCounts !== 0">
              {{
                parseFloat(
                  (record.cjCounts / record.jinxianCounts || 0) * 100
                ).toFixed(2)
              }}%
            </span>
            <span v-else> -- </span>
          </span>
          <span slot="newsCounts" slot-scope="{ text, record }">
            {{ record.jinxianCounts - record.repCounts }}
          </span>

          <span slot="roi" slot-scope="{ text, record }">
            <span v-if="record.chengben !== '0.00'">
              {{
                parseFloat((record.huikuan / record.chengben) * 100).toFixed(2)
              }}
              %
            </span>

            <span v-else> -- </span>
          </span>
        </advance-table>
      </a-card>
    </a-card>
  </div>
</template>
<script>
import { listBizProductInfo } from "@/api/biz/bizProductInfo";

import {
  guanggaochengben,
  heJiGuanggaochengben,
  exportChengBen,
} from "@/api/biz/bizXiansuoChengbenLog";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import { listUser } from "@/api/system/user";
import { listDeptTree } from "@/api/system/dept";
import { findListByCode } from "@/api/biz/sysArea";
export default {
  name: "BizCapBill",
  components: {
    AdvanceTable,
  },
  data() {
    return {
      showAddModal: false,
      showEditModal: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      zjtotal: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 资方结算表格数据
      bizCapBillList: [],
      // 自建结算表格数据
      zjbizCapBillList: [],
      orgTypeOptions: [],
      // 结算类型字典
      typeOptions: [],
      // 结算状态字典
      statusOptions: [],
      dateRange: [],
      // 城市
      cityOptions: [],
      // 标签页
      tabKey: "0",
      // 单渠道回款金额列是否显示
      visHuikuan: false,
      disabledLaiyuanType: false,
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,

        deptId: undefined,

        userName: undefined,

        deptName: undefined,

        jinjianId: undefined,

        cusName: undefined,

        beginQdTime: undefined,

        status: undefined,

        cityName: undefined,

        laiyuanType: undefined,

        isSum: 1,
      },
      hejicolumns: [
        {
          title: "",
          ellipsis: true,
          dataIndex: "heji",
          align: "center",
          width: "60px",
        },
        {
          title: "接入客户",

          ellipsis: true,
          align: "right",
          width: "100px",
          scopedSlots: { customRender: "customers" },
        },
        {
          title: "新客户数",
          // dataIndex: "newCustomers",
          ellipsis: true,
          align: "right",
          width: "100px",
          scopedSlots: { customRender: "newCustomers" },
        },
        {
          title: "重复客户数",
          dataIndex: "repCustomers",
          ellipsis: true,
          align: "right",
          width: "100px",
        },
        {
          title: "成交客户数",
          dataIndex: "cjCustomers",
          ellipsis: true,
          align: "right",
          width: "100px",
        },
        {
          title: "成交率",

          ellipsis: true,
          align: "right",
          width: "100px",
          scopedSlots: { customRender: "chengjiaolv" },
        },
        {
          title: "总成本（元）",
          dataIndex: "zongchengben",
          ellipsis: true,
          align: "right",
          width: "150px",
          scopedSlots: { customRender: "amount" },
        },
        {
          title: "回款金额（元）",
          dataIndex: "huikuanAmount",
          ellipsis: true,
          align: "right",
          width: "150px",
          scopedSlots: { customRender: "amount" },
        },
        {
          title: "投资回报率",
          ellipsis: true,
          align: "right",
          width: "150px",
          scopedSlots: { customRender: "hejiroi" },
        },
      ],
      hejidata: [],
      columns: [
        {
          title: "序号",
          dataIndex: "rowindex",
          ellipsis: true,
          align: "center",
          width: "5%",
          scopedSlots: { customRender: "rowindex" },
        },
        {
          title: "线索来源",
          dataIndex: "laiyuan",
          align: "left",
          width: "20%",
        },
        {
          title: "接入客户",
          dataIndex: "jinxianCounts",
          ellipsis: true,
          align: "right",
          width: "20%",
          scopedSlots: { customRender: "counts" },
        },
        {
          title: "新客户数",
          dataIndex: "newsCounts",
          ellipsis: true,
          align: "right",
          width: "20%",
          scopedSlots: { customRender: "newsCounts" },
        },
        {
          title: "重复客户数",
          dataIndex: "repCounts",
          ellipsis: true,
          align: "right",
          width: "20%",
          scopedSlots: { customRender: "counts" },
        },
        {
          title: "成交客户",
          dataIndex: "cjCounts",
          ellipsis: true,
          align: "right",
          width: "20%",
          scopedSlots: { customRender: "counts" },
        },
        {
          title: "成交率",
          // dataIndex: "repCounts",
          ellipsis: true,
          align: "right",
          width: "20%",
          scopedSlots: { customRender: "cjlv" },
        },
        // {
        //   title: "单条成本(元)",
        //   dataIndex: "danjia",
        //   scopedSlots: { customRender: "amount" },
        //   align: "right",
        //   width: "20%",
        // },

        {
          title: "合计成本（元）",
          dataIndex: "chengben",
          ellipsis: true,
          align: "right",
          width: "20%",
          scopedSlots: { customRender: "amount" },
        },
        {
          title: "回款金额（元）",
          dataIndex: "huikuan",
          ellipsis: true,
          align: "right",
          width: "20%",
          scopedSlots: { customRender: "amount" },
        },
        {
          title: "投资回报率",
          ellipsis: true,
          align: "right",
          width: "150px",
          scopedSlots: { customRender: "roi" },
        },
      ],

      laiyuanOptions: [],
      // 根据岗位删选员工
      postIds: ["gwzg", "rzgw", "qyjl", "sg"],
      // 部门信息
      deptOptions: [],
      userNamesList: [],
      isKefu: 2,
    };
  },
  computed: {
    dynamicColumns() {
      return this.columns.map((col) => {
        // if (col.dataIndex === "huikuan") {
        //   return {
        //     ...col,
        //     visible: this.visHuikuan,
        //   };
        // }
        return col;
      });
    },
  },

  created() {
    this.getList();
    this.getDicts("zifang_jiesuan_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("zifang_jiesuan_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("org_type_options").then((response) => {
      this.orgTypeOptions = response.data;
    });
    this.getDicts("bus_type").then((response) => {
      this.laiyuanOptions = response.data;
    });
    this.getDeptList();
    this.handleFindCityList();
  },
  methods: {
    /** tab选显卡操作 */
    callback(v) {
      this.tabKey = v;
      this.resetQuery();
      if (v === "1") {
        this.queryParam.laiyuanType = "1";
        this.onLaiyuanChange("1");
        this.disabledLaiyuanType = true;
      } else if (v === "2") {
        this.queryParam.laiyuanType = "2";
        this.onLaiyuanChange("2");
        this.disabledLaiyuanType = true;
      } else {
        this.disabledLaiyuanType = false;
      }
    },

    onLaiyuanChange(v) {
      var type = "bus_type";
      if (v === "1") {
        type = "bus_type";
      } else {
        type = "laiyuan_self";
      }
      this.getDicts(type).then((response) => {
        this.laiyuanOptions = response.data;
      });
    },

    // 获取城市区域列表
    handleFindCityList() {
      findListByCode().then((res) => {
        this.cityOptions = res.data;
      });
    },
    getUserList(deptId) {
      const params = {
        pageNum: 1,
        pageSize: 100,
        deptId: deptId,
      };
      if (this.isKefu) {
        params.isKefu = this.isKefu;
      }
      if (this.postIds) {
        params.postIds = this.postIds;
      }
      listUser(params).then((res) => {
        this.userNamesList = res.data.list;
      });
    },
    onMenuTreeChange(value) {
      this.getUserList(value);
    },
    getDeptList() {
      listDeptTree("", 3).then((response) => {
        // this.expandTree(response.data, 3, this.expandedRowKeys);
        this.deptOptions = response.data;
      });
    },
    handleChooseProduct(val, options) {
      // this.form.productId = val;
      // this.form.productName = options.key;
    },
    handleGetProductInfo(value) {
      listBizProductInfo({ orgType: value, pageSize: 50 }).then((res) => {
        this.productList = res.data.list;
      });
    },
    formatNumber(num) {
      return parseFloat(num || 0).toFixed(2);
    },
    /** 查询资方结算列表 */
    getList() {
      this.loading = true;
      this.visHuikuan = this.queryParam.laiyuan !== undefined;
      if (this.tabKey === "1") {
        this.queryParam.laiyuanType = "1";
      } else if (this.tabKey === "2") {
        this.queryParam.laiyuanType = "2";
      }
      guanggaochengben(this.addDateRange(this.queryParam, this.dateRange)).then(
        (response) => {
          this.bizCapBillList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
      heJiGuanggaochengben(
        this.addDateRange(this.queryParam, this.dateRange)
      ).then((res) => {
        this.hejidata = [];
        var data = res.data;
        if (data) {
          data.heji = "合计：";
          this.hejidata.push(data);
        }
      });
    },
    // 结算类型字典翻译
    typeFormat(row) {
      if (row.type) {
        return this.selectDictLabel(this.typeOptions, row.type);
      } else {
        return "";
      }
    },
    // 结算类型字典翻译
    orgTypeFormat(row) {
      if (row.orgType) {
        return this.selectDictLabel(this.orgTypeOptions, row.orgType);
      } else {
        return "";
      }
    },
    // 结算状态字典翻译
    statusFormat(row) {
      if (row.status) {
        return this.selectDictLabel(this.statusOptions, row.status);
      } else {
        return "";
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,

        deptId: undefined,

        userName: undefined,

        deptName: undefined,

        jinjianId: undefined,

        cusName: undefined,

        beginQdTime: undefined,

        status: undefined,

        cityNames: undefined,

        laiyuan: undefined,

        isSum: 1,
      };
      this.handleQuery();
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = size;
      this.getList();
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    handleAdd(record) {
      if (record.status === "1") {
        this.$message.warning("请勿重复结算", 3);
        return;
      }
      this.showAddModal = true;
      this.$nextTick(() => this.$refs.bizCapBillAddForm.handleAdd(record));
    },
    handleUpdate(record, ids) {
      this.showEditModal = true;
      this.$nextTick(() =>
        this.$refs.bizCapBillEditForm.handleUpdate(record, ids)
      );
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportChengBen(that.queryParam).then((response) => {
            that.download(response.msg);
            that.$message.success("导出成功", 3);
          });
        },
        onCancel() {},
      });
    },
  },
};
</script>
